#!/usr/bin/env node

const http = require('http'),
      url = require('url'),
      qs = require('querystring'),
      log = console.log;


let items = [];

function genPage() {
  log(items.length);
  let html = `<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>todo list </title>
    </head>
    <body>
      英文感叹号，ctrl+y，松手，按逗号
      <h1>Todo list</h1>
      <form method="GET" action="http://192.168.145.129:8080">
        <input type="text" name="item">
        <input type="submit" value="submit">
      </form>
      <ul id="item-ul"> 
        ${items.map(item => '<li>'+item+'</li>').join('\n')}
      </ul>
    </body>
  </html>`;
  
  return html;

}

http.createServer((req, res) => {
  let addr = url.parse(req.url);
  let value = qs.parse(addr.query).item;
  if(value !== '' && value !== 'undefined' &&  typeof value !== 'undefined') {
    items.push(value);
  }
  res.writeHead(200, {
    'Content-Type': 'text/html',
    'Content-Lenght': Buffer.byteLength(genPage())        
  });
  res.end(genPage());
}).listen(8080);
